package com.feng.cloud.common.request;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.feng.cloud.common.utils.LambdaUtils;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.util.ClassUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName QueryRequest
 * @Description 请求查询
 * @Author Better Feng
 * @Date 2019/12/19 16:27
 * @Version 1.0
 **/
@EqualsAndHashCode(callSuper = true)
@Getter
@Setter
@ToString
@Accessors(chain = true)
@Slf4j
public class QueryRequest extends LinkedHashMap<String, Object> {

    // 每页显示大小
    private int pageSize = 10;

    // 当前页
    private int pageNum = 1;

    // 排序字段
    private String field;

    // 排序规则，asc升序，desc降序
    private String order;

    /**
     *
     * @param fu SFunction
     * @param <T> T
     * @return E
     */
    public <T,E> E getValue(SFunction<T, ?> fu, Class<E> targetType) {
        String property = LambdaUtils.getProperty(fu);
        Object value = super.get(property);
        if (targetType == null) {
            return (E) value;
        }
        if (ClassUtils.isAssignableValue(targetType, value)) {
            return (E) value;
        }
        ConversionService conversionServiceToUse = DefaultConversionService.getSharedInstance();
        return conversionServiceToUse.convert(value, targetType);
    }

    public QueryRequest(Map<String, Object> params) {
        this.putAll(params);
        Object pageNum = params.get("pageNum");
        if (pageNum != null) {
            int page = Integer.parseInt(pageNum.toString());
            if (page >= 1) {
                this.pageNum = page;
            }
        }
        this.remove("pageNum");
        Object pageSize = params.get("pageSize");
        if (pageSize != null) {
            int limit = Integer.parseInt(pageSize.toString());
            if (50 <= limit) {
                this.pageSize = limit;
            }
            this.pageSize = limit;
        }
        this.remove("pageSize");
        Object field = params.get("field");
        if (field != null) {
            this.field = field.toString();
        }
        this.remove("field");
        Object order = params.get("order");
        if (order != null) {
            this.order = order.toString();
        }
        this.remove("order");
    }
}
